package com.wang.mall.schedule;


import com.wang.mall.service.SkillService;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;


/**
 * 秒杀商品定时上架
 */
@EnableAsync // 开启异步任务功能
@Slf4j
@Component
@EnableScheduling
public class SkillProductSchedule {

    @Autowired
    SkillService skillService;

    @Autowired
    RedissonClient redissonClient;

    /**
     * 上架最近三天的需要参与秒杀的商品
     * 幂等性处理
     */
    @Async
    @Scheduled(cron = "0 * * * * ?")
    public void uploadSkillProduct() {
        // 1.添加分布式锁,限制多个微服务同时执行这个代码
        RLock lock = redissonClient.getLock("seckill:upload:lock");

        try {
            lock.lock(15, TimeUnit.SECONDS);
            log.info("开始秒杀商品上架");
            skillService.uploadSkillProduct();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }
}
